package com.blue.user.mq.config;

import com.blue.user.mq.beans.RabbitBeanUtil;
import com.blue.user.mq.beans.RabbitConnConfig;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

/**
 * 初始化对应环境MQ的队列
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Component
@ConditionalOnProperty(value = {"spring.rmq.enable"})
@DependsOn("multiRabbitMqConfig")
public class InitRabbitQueue implements InitializingBean {

    @Autowired
    private RabbitBeanUtil rabbitBeanUtil;

    /**
     * 初始化队列消息
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("环境: {}{}", RabbitConnConfig.ENV.get(0), "创建队列和交换机信息");
        CachingConnectionFactory connFactory = rabbitBeanUtil.getRabbitConnFactory(0);
        /*lora link 平台 订阅设备心跳消息*/
        this.initQueue(connFactory, "env_01_queue", "", BuiltinExchangeType.TOPIC, "");
        /*lora link 平台 订阅实时数据消息*/
        this.initQueue(connFactory, "env_02_queue", "", BuiltinExchangeType.TOPIC, "");
    }

    /**
     * 根据mq连接工厂创建队列
     */
    private void initQueue(CachingConnectionFactory connectionFactory, String queue, String exchange,
                           BuiltinExchangeType exchangeType, String routingKey) {
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);
        try {
            channel.exchangeDeclare(exchange, exchangeType, true);
            channel.queueDeclare(queue, true, false, false, null);
            channel.queueBind(queue, exchange, routingKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
